package com.zlx.mall.integration.sms.Impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zlx.mall.basic.common.constant.PromptConstants;
import com.zlx.mall.basic.common.exception.IllegalBizArgumentException;
import com.zlx.mall.basic.resource.IResourceService;
import com.zlx.mall.biz.access.enums.SendSwitchEnum;
import com.zlx.mall.biz.resource.BasicResourceEnum;
import com.zlx.mall.integration.sms.ISmsIntegration;
import com.zlx.mall.integration.sms.constant.JuheSmsConstants;
import com.zlx.mall.integration.sms.enums.JuHeResponseEnum;
import com.zlx.mall.integration.sms.exception.JuHeException;
import com.zlx.mall.integration.sms.model.JuheSmsParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.TreeMap;

/**
 * @Author xiatian
 * @Date 2024/5/28 星期二 10:22
 * @注释
 */
@Slf4j
@Service
public class JuheSmsServiceImpl implements ISmsIntegration {
    @Resource
    private IResourceService resourceService;
    String KEY = JuheSmsConstants.KEY;
    String URL = JuheSmsConstants.URL;
    /**
     * 发送短信
     *
     * @param param：
     * @return
     */
    public Boolean sendSingleSms(JuheSmsParam param) {
        log.info("聚合发送短信：{}", JSONUtil.toJsonStr(param));
        String switchCode = resourceService.get(BasicResourceEnum.SMS_VERIFICATION_CODE_SWITCH, String.class, SendSwitchEnum.OPEN.getCode());
        if (SendSwitchEnum.CLOSE.getCode().equals(switchCode)) {
            log.info("短信通道关闭，mock发送结果");
            return true;
        }
        try {
            String url = String.format(URL, param.getMobile(), param.getTplId(),
                    URLEncoder.encode(StrUtil.isEmpty(param.getVariable()) ? "" : param.getVariable() , "utf-8"), KEY);
            HttpRequest get = HttpUtil.createGet(url)
                    .header("Content-Type", "application/json")
                    .timeout(5000);
            //执行请求
            HttpResponse response = get.execute();
            //获取相应内容
            String result = response.body();
            log.info("聚合发送短信的手机号：{}，返回结果：{}", param.getMobile(), result);
            JSONObject jsonResult = JSONUtil.parseObj(result);
            int errorCode = (int) jsonResult.get("error_code");
            if (!NumberUtil.equals(errorCode, 0)) {
                JuHeResponseEnum juHeResponse = JuHeResponseEnum.getByCode(String.valueOf(errorCode));
                if (juHeResponse != null) {
                    throw new JuHeException(juHeResponse);
                }
                throw new IllegalBizArgumentException(PromptConstants.SMS_SENDING_FAILED_PLEASE_TRY_AGAIN_LATER);
            }
        } catch (Exception e) {
            log.error("聚合发送短信错误 = {} ", e.toString());
            //throw new IllegalBizArgumentException(PromptConstants.SMS_SENDING_FAILED_PLEASE_TRY_AGAIN_LATER);
        }
        return true;
    }


    @Override
    public Boolean sendSingleSms(JuheSmsParam params, TreeMap<String, Object> map) {
        StringBuffer var = new StringBuffer();
        if (!map.isEmpty()) {
            for (String key : map.keySet()) {
                var.append("#");
                var.append(key);
                var.append("#=");
                var.append(map.get(key)+"&");
            }
            var.deleteCharAt(var.length() - 1);
        }
        params.setVariable(var.toString());
        this.sendSingleSms(params);
        return true;
    }


}
